package com.juicygames.framework.draw.sprite;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;

public abstract class Animation {
	private static final String LOGTAG = Animation.class.getName();
	
	protected int bitmapResourceId;
	protected int numberOfFrames;
	protected int delay;
	protected boolean playOnlyOnce = false;
	
	private Bitmap spriteSheet;
	private int width;
	private int height;
	
	private int frame;
	private int delayCounter;
	private Rect sourceRect;
	private RectF destinationRect;
	
	private static Paint paint = new Paint();
	
	public Animation() {}
	
	public void load(Resources androidResources) {
		if (numberOfFrames < 1) {
			throw new IllegalArgumentException("numberOfFrames needs to be >= 1. " + numberOfFrames + " passed.");
		}
		
		spriteSheet = BitmapFactory.decodeResource(androidResources,bitmapResourceId);
		
		width = spriteSheet.getWidth() / numberOfFrames;
		height = spriteSheet.getHeight();
		
		this.delayCounter = 0;
		
		sourceRect = new Rect(0,0,width-1,height-1);
		destinationRect = new RectF(sourceRect);
	}
	
	public void stepFrame() {
		if (++delayCounter >= delay) {
			if (++frame >= numberOfFrames && !playOnlyOnce) {
				frame = 0;
			}
			delayCounter = 0;
		}
	}
	
	public void reset() {
		frame = 0;
	}
	
	public void draw(Canvas canvas, float left, float top) {
		
		if (numberOfFrames > 1) {
		
			sourceRect.set(width * frame, 0, width * frame + width - 1, height - 1);
			
			destinationRect.set(left, top, left+width-1, top+width-1);
			
			canvas.drawBitmap(spriteSheet, sourceRect, destinationRect, paint);
			
		} else {
			
			// There's a weird bug that makes us use this line if there's only one frame
			canvas.drawBitmap(spriteSheet, left, top, paint);
			
		}
		
	}
	
	public int getWidth() {
		return width;
	}
	
	public int getHeight() {
		return height;
	}

}
